#include <iostream>
#include <fstream>
#include <iomanip>
#include <sys/types.h>
#include <fcntl.h>

extern "C" {
#include "sis3100_vme_calls.h"
}

#include "StartStop.h"
#include "IOError.h"

using namespace std;

char *devfn               = "/tmp/sis1100_00remote";
u_int32_t startstop_addr  = 0xf000;

u_int32_t sleep_time      = 1000;

int main(int argc,char *argv[])
{
  cerr << "test_StartStop" << endl << endl;

  int crate;
  if( !(crate=open(devfn, O_RDWR, 0)) )
  {
    cerr << "ERROR: could not open \"" << devfn << "\"" << endl;
    exit(1);
  }
  
	cerr << "vmesysreset..." << flush;
	if(int r=vmesysreset(crate)) {
			cerr << "error: vmesysreset() returned " << r << endl << endl;
			cerr.flush(); exit(1);
	}
	sleep(1);
	cerr << "ok\n\n";

	StartStop           startstop(crate,startstop_addr);

  try {

			cerr << "reset startstop module...";
			startstop.reset();
			cerr << "ok\n\n";

			cerr << "Card ID=0x" << hex << startstop.getCardID() << "\n\n";


			cerr << "setting presets...";
 			startstop.setTimerPreset( 100 );
			startstop.setPreset1( 0xffff );
			startstop.setPreset2( 0xffff );
			startstop.setPreset3( 0xffff );
			cerr << "ok\n\n";

			u_int16_t cr_val =
					StartStop::TIMERPRESET_ENABLED
//					| StartStop::COUNTER1_ENABLED
//					| StartStop::COUNTER2_ENABLED
//					| StartStop::COUNTER3_ENABLED
					| StartStop::TB_100ms;
			cerr << "set control register to value 0x" << hex << cr_val << "...";
			startstop.setControlRegister( cr_val );
			cerr << "ok\n\n";

			cerr << "Preset1=0x"     << startstop.getPreset1() << " "
					 << "Preset2=0x"     << startstop.getPreset2() << " "
					 << "Preset3=0x"     << startstop.getPreset3() << " "
					 << "TimerPreset=0x" << startstop.getTimerPreset() << " "
					 << endl << endl;

			cerr << "doing test:\n\n";
			startstop.start();

			time_t start = time(0);
			double dt;

			while(1) {
					u_int16_t status;
					dt=difftime(time(0),start);

					usleep(sleep_time);

					status=startstop.getControlRegister();


					cerr << "\033[1Arunning " << dt << "s"
							 << " status=0x" << hex << status
							 << " counter1=" << startstop.getCounter1()
							 << " counter2=" << startstop.getCounter2()
							 << " counter3=" << startstop.getCounter3()
							 << " timer_counter=" << dec << startstop.getTimerCounter()
							 << " \n";

					if(status & StartStop::COUNTING_FINISHED)
							break;
			}
	} catch(IOError ioe) {
			cerr << "catched IOError:\n"
					 << ioe.getMsg() << "\n"
					 << "param=" << ioe.getParam() << "\n\n";
	}

	cerr << "vmesysreset..." << flush;
	if(int r=vmesysreset(crate)) {
			cerr << "error: vmesysreset() returned " << r << endl << endl;
			cerr.flush(); exit(1);
	}
	sleep(1);
	cerr << "ok\n";

  return 0;
}
